package elven.test.d.common.print;

import java.util.concurrent.ArrayBlockingQueue;

import elven.d.common.log.LogFactory;

public class SamplePrint {
	
	private static int queueSize = 10;
	private static ArrayBlockingQueue<Double> queue = new ArrayBlockingQueue<Double>(queueSize);  
	
	public static void main(String[] args) throws Exception {
		for(int i = 0; i < 100; i++){
			queue.offer(i * 15.2);
		}
		SamplePrint print = new SamplePrint();
		Producer producer =  print.new Producer();
		Consumer consumer = print.new Consumer();
		consumer.start();
		producer.start();
	}
	
	class Consumer extends Thread {
		@Override
		public void run() {
			consumer();
		}
		private void consumer(){
			while(true){
				synchronized (queue) {
                    while(queue.size() == 0){
                        try {
                            LogFactory.d().info("队列空，等待数据");
                            queue.wait();
                        } catch (InterruptedException e) {
                        	LogFactory.d().error(e.getMessage(), e);
                            queue.notify();
                        }
                    }
                    LogFactory.d().info("从队列取走{}元素，队列剩余{}个元素", queue.poll(), queue.size());
                    queue.notify();
                }
			}
		}
	}
	
	class Producer extends Thread{
		@Override
		public void run() {
			producer();
		}
		private void producer(){
			while(true){
				synchronized (queue) {
					while (queue.size() == queueSize) {
						try {
							LogFactory.d().info("队列满了，等待空余空间");
							queue.wait();
						} catch (InterruptedException e) {
							LogFactory.d().error(e.getMessage(), e);
							queue.notify();
						}
						queue.offer(Math.random());
						queue.notify();
						LogFactory.d().info("向队列取中插入一个元素，队列剩余空间：{}", queueSize-queue.size());
					}
				}
			}
		}
	}
	
}
